package phone.qyg.com.qyg.utils;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

/**
 * 作者：lblbh on 2017/11/28 11:37
 * 邮箱：lanbuhan@163.com
 * 功能：app升级
 */
public class AppUpdateUtil {


    static PopupWindow popupUpdateWindow = null;

    public static void appUpdate(String result,View view){

        boolean appUpdateSwitch= SharePrefUtil.getBoolean(SharePrefUtil.KEY.APP_UPDATE_SWITCH,false);
        int available = CommonUtil.isNetworkAvailable(QXApplication.getContext());
        if(available != 0 && available != 1){
            if(appUpdateSwitch)return;
        }
        String appInfoValue = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");
        if(CommonUtil.isRequestStr(appInfoValue)){

            //最大考虑3位数
            String versionValue = JSONTool.jsonDefaluTranString(appInfoValue,JSONTool.Enum.APP_VERSION);
            String lineVersion = JSONTool.requestJSONfindName(versionValue,JSONTool.Enum.LINE_VERSION);
            if(CommonUtil.isRequestStr(lineVersion)){
                String appVersion = CommonUtil.getVersion();
                if(!CommonUtil.isRequestStr(appVersion)) return;

                String lochAppVersion = appVersion.replace(".","0");
                String lineAppVersion = lineVersion.replace(".","0");

                if(Integer.valueOf(lineAppVersion) > Integer.valueOf(lochAppVersion)){
                    SystemPrintl.systemPrintl("需要升级");
                    String msgHint = JSONTool.requestJSONfindName(versionValue,JSONTool.Enum.APP_MESSAGE);
                    String titleHint = JSONTool.requestJSONfindName(versionValue,JSONTool.Enum.APP_TITLE);
                    final String url = JSONTool.requestJSONfindName(versionValue,JSONTool.Enum.APP_URL)+"?time="+System.currentTimeMillis();
//                    final String url = "http://test.nmge-sports.com/androidinstall/vsdkfdskfds13123.shtml";
                    SystemPrintl.systemPrintl("下载的url--->>>"+url);
                    //http://g.pc6.com/9268085437/apk/budejie_6.3.0.apk
                    SystemPrintl.systemPrintl("下载的地址--->>>"+CommonUtil.getSDPath()+ File.separator + ApplicationConfig.SD_FIEL_NAME);
                    popupUpdateWindow = PopuUpdateApp.setPopuAppUpdate(view, titleHint,msgHint, new PopuUpdateApp.OnClickState() {
                        @Override
                        public void OnItemClick(final TextView view, boolean isState) {
                            if(isState){
                                RequestParams params = new RequestParams(url);
//自动为文件命名
                                params.setAutoRename(false);
                                params.setSaveFilePath(CommonUtil.APP_HOST_PATH_APK + File.separator+"com.qyg.phone."+System.currentTimeMillis()+".apk");
                                x.http().get(params, new Callback.ProgressCallback<File>() {
                                    @Override
                                    public void onSuccess(File result) {
                                        //apk下载完成后，调用系统的安装方法
                                        if(popupUpdateWindow != null && popupUpdateWindow.isShowing()){
                                            popupUpdateWindow.dismiss();
                                        }
                                        String path = result.getPath();
                                        SystemPrintl.systemPrintl("下载到的地址是:"+path);
                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                        intent.setDataAndType(Uri.parse("file://"+path), "application/vnd.android.package-archive");
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//创建新的任务栈来存放新的Activity
                                        QXApplication.getContext().startActivity(intent);
                                    }
                                    @Override
                                    public void onError(Throwable ex, boolean isOnCallback) {
                                        SystemPrintl.systemPrintl("下载失败");
                                    }
                                    @Override
                                    public void onCancelled(CancelledException cex) {
                                    }
                                    @Override
                                    public void onFinished() {
                                    }
                                    //网络请求之前回调
                                    @Override
                                    public void onWaiting() {
                                    }
                                    //网络请求开始的时候回调
                                    @Override
                                    public void onStarted() {
                                    }
                                    //下载的时候不断回调的方法
                                    @Override
                                    public void onLoading(final long total, final long current, boolean isDownloading) {
                                        //当前进度和文件总大小
                                        SystemPrintl.systemPrintl("current："+ current +"，total："+total);

                                        CommonUtil.runOnUIThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if(total == 0){
                                                    view.setText("正在下载中...");
                                                }else{
                                                    int progress = (int) ((current * 100) /total);
                                                    view.setText("下载"+progress+"%");
                                                }
                                            }
                                        });
                                    }
                                });
//

                            }
                        }
                    });
                }

            }
        }
    }
}
